import { Injectable } from '@angular/core';
import { Http, Headers } from '@angular/http';
import { ApiService } from './api.service';
import { People} from '../people';
import { findReadVarNames } from '@angular/compiler/src/output/output_ast';
import {resolve} from 'url';
import { Observable } from 'rxjs';
import { catchError, map, tap } from 'rxjs/operators';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import {el} from '@angular/platform-browser/testing/src/browser_util';

@Injectable({
  providedIn: 'root',
})
export class PeopleService {
  private api_url ;
  private headers ;

  constructor(private http: Http, private apiService: ApiService) {
    this.api_url = apiService.getUrl() + '/people';
    this.headers = apiService.getHeaders();
  }
  getPeople(): Promise<People[]> {
    const url = `${this.api_url}`;
    return this.http.get(url, {headers: this.headers})
      .toPromise()
      .then(res => res.json() as People[])
      .catch(this.handleError);
  }
  getPeopleByPid(pid: string): Promise<People> {
    const url = `${this.api_url}?pid=${pid}`;
    console.log(url);
    return this.http.get(url, {headers: this.headers})
      .toPromise()
      .then(res => res.json() as People)
      .catch(this.handleError);
  }
  updateCount(people: People): Promise<People> {
    const url = `${this.api_url}/${people.id}`;
    return this.http
      .put(url, JSON.stringify(people), {headers: this.headers})
      .toPromise()
      .then(res => res.json() as People)
      .catch(this.handleError);
  }
  // 根据所有属性添加读者
  createReaderByAll(rname: string, pid: number, password: string, position: number, count:number): Promise<People> {
    const people = {
      pid: pid,
      password: password,
      position: position,
      rname: rname,
      count: count
    }
    const url = `${this.api_url}`;
    return this.http
      .post(url, JSON.stringify(people), {headers: this.headers})
      .toPromise()
      .then(res => res.json() as People)
      .catch(this.handleError);
  }

  private handleError(error: any): Promise<any> {
    console.error('An error occurred', error);
    return Promise.reject(error.message || error);
  }

}
